package com.instalinks.android.smspostservice.receiver;

import java.lang.reflect.Method;
import java.util.Hashtable;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.internal.telephony.ITelephony;
import com.instalinks.android.lib.AppHelper;
import com.instalinks.android.lib.UrlData;
import com.instalinks.android.lib.UrlResponse;
import com.instalinks.android.smspostservice.utils.AppConfig;
import com.instalinks.android.smspostservice.utils.enums.ConfigParams;
import com.instalinks.android.smspostservice.utils.enums.PhoneParams;
import com.instalinks.android.smspostservice.utils.enums.ServiceStartStatus;

public class CallReceiver extends BroadcastReceiver {
	Context mContext;
	AppConfig mAppConfig;

	private String sender = "MISSED_CALL";
	private String incomingNumber = "";
	private boolean autoReply = false;

	@Override
	public void onReceive(Context context, Intent intent) {
		mContext = context;
		mAppConfig = new AppConfig(context);

		autoReply = mAppConfig.isAutoReplyFlag();

		String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
		if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
			incomingNumber = intent
					.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
			disconnect();
		}
	}

	@SuppressWarnings("rawtypes")
	private void disconnect() {
		try {
			TelephonyManager manager = (TelephonyManager) mContext
					.getSystemService(Context.TELEPHONY_SERVICE);
			Class c = Class.forName(manager.getClass().getName());
			Method m = c.getDeclaredMethod("getITelephony");
			m.setAccessible(true);
			ITelephony telephony = (ITelephony) m.invoke(manager);
			telephony.endCall();
			logIncomingCall();
		} catch (Exception e) {
			mAppConfig.alert("error in disconnect : " + e.getMessage());
			Log.d("2WAY", e.getMessage());
		}
	}

	private void logIncomingCall() {
		mAppConfig.rePopulate();

//		ServiceStartStatus status = mAppConfig.allGoodToRunService();
		if (!mAppConfig.isValidDataNetwork() || mAppConfig.is2GNetwork()){ //(status != ServiceStartStatus.Ok) {
			decreaseAvailableFreeCount();

			mAppConfig.handleServiceResponse(ServiceStartStatus.Non2gNetworkRequired);
			return;
		}

		UrlResponse response = postMissedCallRecord();
		boolean isSuccess = (response.getResponseType() == UrlResponse.UrlResponseType.success);

		saveCounts(isSuccess);

		if (isSuccess) {
			if (autoReply) {
				AppHelper.sendSms(mContext, incomingNumber, response.getMessage());
			}
		} else {
			if (autoReply) {
				AppHelper
						.sendSms(mContext, incomingNumber, mAppConfig.getFailReplyMsg());
			}
			mAppConfig.alert(response.getMessage());
		}
	}

	private void saveCounts(boolean isSuccess) {
		try {
			int successCount = mAppConfig.getCallSuccessCount()
					+ (isSuccess ? 1 : 0);
			mAppConfig.setCallSuccessCount(successCount);
		} catch (Exception e) {
			mAppConfig.alert("Error saving successcounts");
		}

		try {
			int failedCount = mAppConfig.getCallFailedCount()
					+ (isSuccess ? 0 : 1);
			mAppConfig.setCallFailedCount(failedCount);
		} catch (Exception e) {
			mAppConfig.alert("Error saving failedcounts");
		}

		decreaseAvailableFreeCount();
	}

	private void decreaseAvailableFreeCount() {
		try {
			int availableFreeCount = mAppConfig.getAvailableFreeCount() - 1;
			mAppConfig.setAvailableFreeCount(availableFreeCount);
		} catch (Exception e) {
			mAppConfig.alert("Error saving availablefreecounts");
		}
	}

	private UrlResponse postMissedCallRecord() {
		Hashtable<String, String> htParams = mAppConfig.getDataPostHashtable();

		htParams.put(ConfigParams.mode.toString(), ConfigParams.modes.urlpost.toString());
		htParams.put(PhoneParams.sender.toString(), sender);
		htParams.put(PhoneParams.text.toString(), incomingNumber);

		UrlData data = new UrlData(mAppConfig.getDataPostUrl(), 5000);
		UrlResponse res = data.postData(htParams);

		return res;
	}
}
